﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Kaskelot.SP.Model.Client.Forms;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientPersonTypExtensions
	{
		public static ClientPersonTyp ToClientContract(this PersonTyp entity)
		{
			ClientPersonTyp b = new ClientPersonTyp();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static ClientPersonTyp ToMinimalClientContract(this PersonTyp entity)
		{
			ClientPersonTyp b = new ClientPersonTyp();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static PersonTyp ToContract(this ClientPersonTyp b)
		{
			PersonTyp entity = new PersonTyp();

			CopyToEntity(b, entity);

			return entity;
		}

		public static PersonTyp UpdateContract(this PersonTyp pt, PersonTypForm form)
		{
			if (pt.Id == Guid.Empty)
				pt.Id = Guid.NewGuid();

			pt.Namn = form.Namn;

			return pt;
		}

		private static void CopyFromEntity(PersonTyp from, ClientPersonTyp to, bool minimal)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;

			to.Namn = from.Namn;

			if (from.Andrad.HasValue)
				to.Andrad = from.Andrad.Value.ToShortDateString();
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad.ToShortDateString();
			to.SkapadAv = from.SkapadAv;
		}

		private static void CopyToEntity(ClientPersonTyp from, PersonTyp to)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;

			to.Namn = from.Namn;

			to.Andrad = DateTime.Parse(from.Andrad);
			to.AndradAv = from.AndradAv;
			to.Skapad = DateTime.Parse(from.Skapad);
			to.SkapadAv = from.SkapadAv;
		}
	}
}
